#include "listwidget.h"
#include <QApplication>
#include <QMimeData>
#include <QDrag>
#include <QObject>

ListWidget::ListWidget(QWidget* parent /*= nullptr*/):
    QListWidget (parent)
{
    setAcceptDrops(true);
}

void ListWidget::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
            startPos = event->pos(); // 记录开始点坐标
    ListWidget::mousePressEvent(event);
}

void ListWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) // 等同于 event->buttons() == Qt::LeftButton
    {
        int distance = (event->pos() - startPos).manhattanLength(); // 哈夫曼距离（两点间的距离公式）
        if (distance >= QApplication::startDragDistance()) // QApplication::startDragDistance()是一个预设的防抖动的安全距离
            performDrag();  // 展示拖动
    }
    ListWidget::mouseMoveEvent(event);
}

void ListWidget::dragEnterEvent(QDragEnterEvent *event)
{

}

void ListWidget::dragMoveEvent(QDragMoveEvent *event)
{
    QObject* source = event->source();
    if (source && source != this) {
           event->setDropAction(Qt::MoveAction);
           event->accept();
    }
}

void ListWidget::dropEvent(QDropEvent *event)
{
    //MainWindow *source = qobject_cast(event->source());
    QObject* source = event->source();
    if (source && source != this) {
        addItem(event->mimeData()->text());
    event->setDropAction(Qt::MoveAction);
    event->accept();
    }
}

void ListWidget::performDrag()
{
    ListWidgetItem *item = currentItem();
    if(item)
    {
        QMimeData *mimeData = new QMimeData;
        mimeData->setText(item->text());

        QDrag* drag = new QDrag(this);
        drag->setMimeData(mimeData);
        //drag->setPixmap("C:/Users/Grozta/Desktop/QT/QtDrapAndDrop2List/1.png");
        if (drag->exec(Qt::MoveAction) == Qt::MoveAction)
                    delete item;
    }
}

